<template>
	<div class="page-card">
		<el-button @click="onAddClass()" type="primary">添加</el-button>
		<el-button @click="onDel()" type="danger">批量删除</el-button>
	</div>
	<div class="page-card">
		<el-table :data="postList" @selection-change="handleSelectionChange" v-loading="loading">
			<el-table-column type="selection" width="55" />
			<el-table-column prop="name" label="类目名称" show-overflow-tooltip />
			<el-table-column fixed="right" label="操作" width="120">
				<template #default="scope">
					<el-button @click="onEdit(scope.row.id)" type="primary" link>编辑</el-button>
					<el-button @click="onDel(scope.row, scope.$index)" type="danger" link>删除</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>

	<!-- 编辑弹窗 -->
	<el-dialog v-model="showEdit" :title="dialogTitle" width="30%">
		<el-form :model="dataForm" label-width="120px">
			<el-form-item label="类目名称">
				<el-input v-model="dataForm.name" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit">保存</el-button>
				<el-button @click="showEdit = false">取消</el-button>
			</el-form-item>
		</el-form>
	</el-dialog>
</template>
<script setup>
import { ref, onMounted, reactive } from "vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import { classList, categorySave, categoryInfo, categoryDelete } from '@/api/topic'

let postList = ref([]);
let selectIds = ref([]);
let loading = ref(false);
const showEdit = ref(false);
const dialogTitle = ref('');
const dataForm = reactive({
	id: '',
	name: ''
})

onMounted(function () {
	getPostList();
})

function onAddClass() {
	showEdit.value = true;
	dialogTitle.value = '添加类目'
}

function onEdit(id) {
	showEdit.value = true;
	dialogTitle.value = '编辑类目'

	categoryInfo({ id }).then(res => {
		dataForm.id = res.result.id;
		dataForm.name = res.result.name;
	})
}

function getPostList() {
	loading.value = true;
	classList().then(res => {
		postList.value = res.result;

		loading.value = false;
	});
}

function handleSelectionChange(e) {
	let ids = [];
	e.forEach(item => {
		ids.push(item.id)
	})

	selectIds.value = ids;
}

function onDel(row, index) {
	ElMessageBox.confirm(
		'确认删除?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}
	).then(() => {
		let ids = []
		if (row) {
			ids.push(row.id)
		} else {
			ids = selectIds.value
		}

		categoryDelete({
			ids
		}).then(res => {
			if (res.code == 1) {
				getPostList();
				ElMessage({
					type: 'success',
					message: '删除成功',
				})
			} else {
				ElMessage({
					type: 'error',
					message: '删除失败',
				})
			}
		})
	})
}

function onSubmit() {
	categorySave(dataForm).then(res => {
		if (res.code == 1) {
			ElMessage({
				type: 'success',
				message: '删除成功',
			})

			getPostList();

			showEdit.value = false
		}
	})
}
</script>

<style lang="scss" scoped="scoped">
.img-wrap {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	grid-gap: 2px;

	img {
		width: 100%;
		height: 80px;
	}
}
</style>
